
#include "../include/qtwi/core/iiwidgets.hpp"


//QITextBox

QITextBox::QITextBox(QIWidget *parent, const QString &, int x, int y, ITextBox::Mode mode)
{
	rtti_qiradiogroup_parent(QTextEdit);

	QTextEdit::move(x, y);

	QTextEdit::setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
	QTextEdit::setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
	
	QTextEdit::setLineWrapMode(QTextEdit::NoWrap); // Fixme: ITextBox::Mode?

	// Hide scrollbars
	if(mode == ITextBox::Single) {
		QList<QWidget*> lst(QTextEdit::scrollBarWidgets(Qt::AlignVertical_Mask));
		for(QList<QWidget*>::iterator i = lst.begin(); i != lst.end(); i++) {
			(*i)->hide();
		}
	}

	if(mode == ITextBox::Single) {
		QTextEdit::setTabChangesFocus(true);
	}
		
	QTextEdit::zoomOut();
}

#include <QTextCursor>

void QITextBox::appendText(const char *txt) 
{
	const QString t(txt);
	const QString tlt(text().c_str());
	setText((tlt + t).toStdString().c_str());
	
	// Autoscroll; this is somewhat screwed up
	QTextEdit::ensureCursorVisible();
	QTextEdit::textCursor().movePosition(QTextCursor::End);
	QScrollBar *sbar = QTextEdit::verticalScrollBar();
	sbar->setValue(sbar->maximum());
	QTextCursor curse =  QTextEdit::textCursor();
	curse.movePosition(QTextCursor::End);
	QTextEdit::setTextCursor(curse);
}

void TITextBox::appendText(const char* txt) 
{
	
	std::string current = text();
	current += std::string(txt);
	setText(const_cast<char*>(current.c_str()));

	/*
		
	  GR_EVENT_BUTTON e;
	  GR_EVENT *pe = reinterpret_cast<GR_EVENT*>(&e);
		  
	  GrSetFocus(THIS_TWG->wid);
	  THIS_TWG->status.hasfocus = GR_TRUE;

	  pe->type = GR_EVENT_TYPE_BUTTON_DOWN;
	  pe->button.subwid = 0;
	  pe->keystroke.ch = MWKEY_DOWN;

		
	  DrawTextBox(THIS_TWG, 1);

	*/

	if(*txt == '\n') {
		// FIXME: This is hacky but all else just wouldn't work
		GrInjectPointerEvent(THIS_TWG->props.posx+
				     0.75*THIS_TWG->props.width, THIS_TWG->props.posy+
				     THIS_TWG->props.height , 1, 0);
		GrInjectKeyboardEvent(THIS_TWG->wid, MWKEY_DOWN, 0, 0, 1);
	}
}

// IScrollbar

QIScrollbar::QIScrollbar(QIWidget *parent, const int &x, const int &y, const int &min, 
			 const int &max, const int &step, const int &page,
			 IScrollbar::Orientation o) :
	QScrollBar((o == IScrollbar::Horizontal) ? (Qt::Horizontal) : (Qt::Vertical), parent)
{
	
	rtti_qiradiogroup_parent(QScrollBar);
	
	QScrollBar::move(x, y);
	QScrollBar::setRange(min, max);
	QScrollBar::setSingleStep(step);
	QScrollBar::setPageStep(page);
		
}

// IProgressBar
void TIProgressBar::resize(int w, int h) 
{
	int new_w = w - label_w - 10;
	TIWidget::resize(new_w, h);
	tnMoveAndResizeWidget(**l, THIS_TWG->props.posx + new_w + 5, 
			      THIS_TWG->props.posy + h - (**l)->props.height,
			      (**l)->props.width, (**l)->props.height);
}

void TIProgressBar::setCurrent(const int &val)
{
	cur = val;
	tnProgressBarUpdate(THIS_TWG, currentPercent());
	std::string txt = _qtwi_to_string(currentPercent()) + "%";
	l->setText(txt);
}
